<template>
  <view class="login-container">
    <view class="login-box">
      <view class="logo-container">
        <view class="logo">logo</view>
      </view>
      <view class="title">欢迎登录</view>
      <view class="form-container">
        <view class="input-group">
          <input
            type="number"
            v-model="formData.phone"
            placeholder="请输入手机号"
            class="input"
            maxlength="11"
            @input="validatePhone" />
          <text class="error-text" v-if="errors.phone">
            {{ errors.phone }}
          </text>
        </view>
        <view class="input-group">
          <input
            :type="showPassword ? 'text' : 'password'"
            v-model="formData.password"
            placeholder="请输入密码"
            class="input"
            @input="validatePassword" />
          <text class="error-text" v-if="errors.password">
            {{ errors.password }}
          </text>
        </view>
        <button
          class="login-btn"
          :class="{ 'login-btn-active': isFormValid }"
          @click="handleSubmit">
          登录
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      formData: {
        phone: "",
        password: "",
      },
      errors: {
        phone: "",
        password: "",
      },
      showPassword: false,
    };
  },
  computed: {
    ...mapGetters(["isLogin", "uid", "userInfo"]),
    isFormValid() {
      return (
        this.formData.phone &&
        this.formData.password &&
        !this.errors.phone &&
        !this.errors.password
      );
    },
  },
  onLoad() {},
  methods: {
    validatePhone() {
      this.errors.phone = "";
      if (!this.formData.phone) {
        return false;
      }
      if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        this.errors.phone = "请输入有效的手机号";
        return false;
      }
      return true;
    },
    validatePassword() {
      this.errors.password = "";
      if (!this.formData.password) {
        return false;
      }
      if (this.formData.password.length < 6) {
        this.errors.password = "密码长度不能少于6个字符";
        return false;
      }
      return true;
    },
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },
    getUrlParameter(name) {
      // const urlParams = new URLSearchParams(window.location.search);
      // return urlParams.get(name);

      const url = window.location.href;
      // 匹配 #/?code=xxx 或 ?code=xxx（兼容不同路由模式）
      const regex = /[#&?]code=([^&]+)/;
      const match = url.match(regex);
      return match ? match[1] : null;
    },
    async handleSubmit() {
      const phoneValid = this.validatePhone();
      const passwordValid = this.validatePassword();
      if (!this.formData.phone) {
        this.errors.phone = "手机号不能为空";
      }
      if (!this.formData.password) {
        this.errors.password = "密码不能为空";
      }
      if (
        !phoneValid ||
        !passwordValid ||
        !this.formData.phone ||
        !this.formData.password
      ) {
        return;
      }
      try {
        // uni.showLoading({
        //   title: "登录中...",
        // });
        this.$Api.user
          .userLogin({
            account: this.formData.phone,
            password: this.formData.password,
          })
          .then((res) => {
            console.log(res.data.data.wxurl, 23234);
            this.$store.commit("UPDATE_USERINFO", res.data.data.userinfo);
            this.$store.commit("LOGIN", res.data.data.userinfo);
            if (res.data.data.userinfo.openid == "") {
              window.location.href = res.data.data.wxurl;
              return;
            }

            uni.showToast({
              title: "登录成功",
              icon: "none",
            });

            setTimeout(() => {
              uni.navigateTo({
                url:
                  "/pages/order/waitOrder?code=" + this.getUrlParameter("code"),
              });
            }, 500);
          });
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: "登录失败，请重试",
          icon: "none",
        });
        console.error("登录失败：", error);
      }
    },
  },
};
</script>

<style>
.login-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: linear-gradient(to bottom, #d6f4ff, #ffffff);
}

.login-box {
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 0 20px;
  box-sizing: border-box;
}

.logo-container {
  display: flex;
  justify-content: center;
  margin-top: 80px;
  margin-bottom: 30px;
}

.logo {
  width: 80px;
  height: 80px;
  background-color: #4084f0;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 20px;
  font-size: 18px;
}

.title {
  font-size: 18px;
  text-align: center;
  margin-bottom: 60px;
  color: #333;
}

.form-container {
  width: 100%;
}

.input-group {
  margin-bottom: 30px;
  position: relative;
}

.input {
  width: 100%;
  height: 44px;
  padding: 0;
  border: none;
  border-bottom: 1px solid #e0e0e0;
  font-size: 16px;
  box-sizing: border-box;
  background-color: transparent;
}

.input::placeholder {
  color: #999;
}

.input:focus {
  border-color: #4084f0;
  outline: none;
}

.error-text {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  display: block;
}

.login-btn {
  width: 100%;
  height: 45px;
  background-color: #4084f0;
  border: none;
  border-radius: 4px;
  color: white;
  font-size: 16px;
  margin-top: 40px;
  opacity: 0.9;
  transition: opacity 0.3s;
}

.login-btn-active {
  opacity: 1;
}

.login-btn:after {
  border: none;
}

.footer-line {
  width: 100%;
  height: 1px;
  margin-top: 80px;
  border-bottom: 1px solid #e0e0e0;
}

.password-toggle {
  display: none;
}
</style>
